const https = require('https')
console.log(https)

function getTableData(id, tab) {
    let host = "https://docs.qq.com",
      callback = "clientVarsCallback";
    let url = `/dop-api/opendoc?id=${id}&tab=${tab}&normal=1&outformat=1&callback=${callback}`;

    return new Promise((resolve, reject) => {
      https
        .get({
          host: 'docs.qq.com',
          path: url,
          headers: {
              'Referer': 'https://docs.qq.com/sheet'
          }
        }, (res) => {
          // 设置字符编码
          res.setEncoding("utf8");

          // 接收数据
          let html = "";
          res.on("data", (chunk) => {
            html += chunk;
          });
          res.on("end", () => {
            resolve(html);
          });
        })
        .on("error", (e) => {
          reject(e);
        });
    }).catch(() => {});
  }

window.clientVarsCallback = function (e) {
  let str = e.split('\n');
  let json = null
  str.some(item => {
    try {
      let jsonStr = ("" + item).replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&#34;/g, '"').replace(/&#39;/g, "'")
      if (jsonStr[0] === "{") json = JSON.parse(jsonStr)
    } catch (err) {
      json = null
    }
    return !!json
  })
  window.openDocResponseText = json
}


window.GetGameDataList = {
  docids: [
    'DR25zc3hUYkFFUWpm', // 黑名单ID
    'DS2NKSURpSHFYRENq', // 房主表ID
    'DS3JFZ0d4QWtJSHhV', // QQ群表ID
    'DS216d0tLU1JxRGVs', // 规则文档ID
  ],
  /**
   * 读取黑名单
   */
  readBlackList() {
    let id = this.docids[0]
    return new Promise(async (resolve, reject) => {
      let html = await getTableData(id)
      eval(html);
      console.log('777777777777777', window.openDocResponseText)
      let data =
        window.openDocResponseText.clientVars.collab_client_vars
          .initialAttributedText.text[0][4][0].c[1];
      let text = [],
        cols = 26,
        rows = -1;
      Object.keys(data).forEach((index) => {
        let val = "";
        if (data[index] && data[index][2] && data[index][2][1])
          val = data[index][2][1];
        if (index >= cols * 2) {
          if (index % cols === 0) rows += 1;
          text[rows] = text[rows] || [];
          text[rows].push(val);
        }
      });
      let black_list = text
        .map((item) => {
          return {
            name: item[0],
            id: item[1],
            result: item[2],
            admin: item[3],
            remark: item[4],
          };
        })
        .filter((item) => item.name);
      resolve(black_list);
    });
  },
  /**
 * 发送请求获取表格数据
 * @param {*} url
 * @returns
 */
  getTableData(id, tab) {
    let host = "https://docs.qq.com",
      callback = "clientVarsCallback";
    let url = `/dop-api/opendoc?id=${id}&tab=${tab}&normal=1&outformat=1&callback=${callback}`;

    return new Promise((resolve, reject) => {
      https
        .get({
          host: 'docs.qq.com',
          path: url,
          headers: {
              'Referer': 'https://docs.qq.com/sheet'
          }
        }, (res) => {
          // 设置字符编码
          res.setEncoding("utf8");

          // 接收数据
          let html = "";
          res.on("data", (chunk) => {
            html += chunk;
          });
          res.on("end", () => {
            resolve(html);
          });
        })
        .on("error", (e) => {
          reject(e);
        });
    }).catch(() => {});
  },
  /**
   * 读取房主列表
   */
  readHomeOwner() {
    let id = this.docids[1]
    return new Promise(async (resolve, reject) => {
      let html = await getTableData(id)
      eval(html);
      console.log('666666', window.openDocResponseText)
      let data =
            window.openDocResponseText.clientVars.collab_client_vars
              .initialAttributedText.text[0][2][0].c[1];
          let text = [],
            cols = 26,
            rows = -1;
          Object.keys(data).forEach((index) => {
            let val = "";
            if (data[index] && data[index][2] && data[index][2][1])
              val = data[index][2][1];
            if (index >= cols * 2) {
              if (index % cols === 0) rows += 1;
              text[rows] = text[rows] || [];
              text[rows].push(val);
            }
          });
          let black_list = text
            .map((item) => {
              return {
                name: item[0],
              };
            })
            .filter((item) => item.name);
          resolve(black_list);
    });
  },
  /**
   * 读取QQ群列表
   */
  readQqGroup () {
    let id = this.docids[2]
    return new Promise(async (resolve, reject) => {
      let html = await getTableData(id)
      eval(html);
      console.log('555555', window.openDocResponseText)
      
      let data =
        window.openDocResponseText.clientVars.collab_client_vars
        .initialAttributedText.text[0][3][0].c[1];
      let text = [],
        cols = 26,
        rows = -1;
      Object.keys(data).forEach((index) => {
        let val = "";
        if (data[index] && data[index][2] && data[index][2][1])
          val = data[index][2][1];
        if (index >= cols * 2) {
          if (index % cols === 0) rows += 1;
          text[rows] = text[rows] || [];
          text[rows].push(val);
        }
      });
      let qq_group_list = text
        .map((item) => {
          return {
            num: item[0],
            link: item[1],
          };
        })
        .filter((item) => item.num);
      resolve(qq_group_list);
    });
  },
  /**
   * 读取规则图片
   */
  readRules() {
    let id = this.docids[3]
    return new Promise(async (resolve, reject) => {
      let html = await getTableData(id)
      eval(html);
      console.log('444444', window.openDocResponseText)

      let data = openDocResponseText.clientVars.collab_client_vars.apool.numToAttrib
      let imageList = []
      for (let i in data) {
        if (data[i][0] === 'img') imageList.push(data[i][1])
      }
      resolve(imageList)
    });
  }
}
